<template>
    <div id="loginBody">
        <!--        标题      -->
        <div id="title">
            <i class="iconfont icon-moneybag"/>
            <div id="titleText">班费管理系统</div>
        </div>
        <!--        登录      -->
        <div class="container" id="login">
            <div class="text">登 录</div>
            <el-form :model="loginData" :rules="rules" ref="loginForm" status-icon>
                <el-form-item prop="userAccount">
                    <el-input v-model="loginData.userAccount" placeholder="账号" :prefix-icon="User"/>
                </el-form-item>
                <el-form-item prop="userPWD">
                    <el-input v-model="loginData.userPWD" placeholder="密码" :prefix-icon="Lock" show-password/>
                </el-form-item>
                <el-link id="forget" type="primary" href="#" @click="forgetPassword">忘记密码?</el-link>
                <el-form-item>
                    <el-button class="button" type="primary" @click="login">登 录</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button class="button" type="primary" @click="toRegisterOrLogin">注 册</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!--        注册      -->
        <div class="container" id="register">
            <div class="text">注 册</div>
            <el-form ref="registerForm" :model="registerData" :rules="rules" status-icon>
                <el-form-item prop="userName">
                    <el-input v-model="registerData.userName" placeholder="用户名" :prefix-icon="User"/>
                </el-form-item>
                <el-form-item prop="userAccount">
                    <el-input v-model="registerData.userAccount" placeholder="账号" :prefix-icon="User"/>
                </el-form-item>
                <el-form-item prop="userPWD">
                    <el-input v-model="registerData.userPWD" placeholder="密码" :prefix-icon="Lock" show-password/>
                </el-form-item>
                <el-form-item prop="userPWD2">
                    <el-input v-model="registerData.userPWD2" placeholder="确认密码" :prefix-icon="Lock"
                              show-password/>
                </el-form-item>
                <el-form-item prop="userPhone">
                    <el-input v-model="registerData.userPhone" placeholder="手机号" :prefix-icon="Phone"/>
                </el-form-item>
                <el-form-item prop="userEmail">
                    <el-input v-model="registerData.userEmail" placeholder="邮箱" :prefix-icon="ChatDotRound"/>
                </el-form-item>
                <el-form-item>
                    <el-button class="button" type="primary" @click="register">注 册</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button class="button" type="primary" @click="toRegisterOrLogin">登 录</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!--        日历      -->
        <el-calendar id="calendar"/>
    </div>
</template>

<script>
//请求
import request from '@/utils/requset.js';
//顶部提示信息
import prompt from '@/utils/prompt.js';
//css
import "../assets/Login.css"
import {ChatDotRound, Lock, Phone, User} from "@element-plus/icons-vue";
//加密
import encrypt from '@/utils/encrypt.js';

export default {
    name: 'LoginAndRegister',
    //element-plus icon
    computed: {
        ChatDotRound() {
            return ChatDotRound
        },
        Phone() {
            return Phone
        },
        Lock() {
            return Lock
        },
        User() {
            return User
        }
    },
    data() {
        return {
            //登录与注册页面切换
            loginDisplay: "block",
            registerDisplay: "none",
            //登录数据
            loginData: {
                userAccount: '',
                userPWD: '',
            },
            //注册数据
            registerData: {},
            //表单校验规则
            rules: {
                userName: [
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                    {min: 1, max: 10, message: '用户名长度为1-12位', trigger: 'blur'},
                ],
                userAccount: [
                    {required: true, message: '请输入账号', trigger: 'blur'},
                    {min: 6, max: 20, message: '账号长度为6-20位', trigger: 'blur'},
                ],
                userPWD: [
                    {required: true, message: '请输入密码', trigger: 'blur'},
                    {min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur'},
                ],
                userPWD2: [
                    {required: true, message: '请输入确认密码', trigger: 'blur'},
                    {min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur'},
                ],
                userPhone: [
                    {required: true, message: '请输入手机号', trigger: 'blur'},
                    {min: 11, max: 11, message: '手机号长度为11位', trigger: 'blur'},
                ],
                userEmail: []
            }
        }
    },
    created() {
        //清除本地存储的用户信息
        localStorage.removeItem("token");
        localStorage.removeItem("userInfo");
    },
    methods: {
        toRegisterOrLogin() {
            //交换loginDisplay与registerDisplay的值
            let temp = this.loginDisplay;
            this.loginDisplay = this.registerDisplay;
            this.registerDisplay = temp;
            //更新登录与注册页面的display
            document.getElementById("login").style.display = this.loginDisplay;
            document.getElementById("register").style.display = this.registerDisplay;
        },
        //登录
        login() {
            //表单校验
            this.$refs["loginForm"].validate(valid => {
                //校验通过
                if (valid) {
                    //获取公钥
                    request.get(
                        "key/getPublicKey"
                    ).then(result => {
                        let backupData = this.backup(this.loginData);
                        //使用公钥加密账号密码
                        this.loginData = this.encrypt(result.data.publicKey, this.loginData);
                        //将加密的数据发送到服务器
                        request.post(
                            "/user/login",
                            this.loginData
                        ).then(result => {
                            prompt(result.message, result.type);
                            if (result.code === "200") {
                                this.$router.push({
                                    path: "/home",
                                });
                                //存储用户信息到浏览器
                                localStorage.setItem("token", result.data.token);
                                localStorage.setItem("userInfo", JSON.stringify(result.data.userInfo));
                            }
                        });
                        this.loginData = this.recovery(this.loginData, backupData);
                    });
                    return;
                }
                //校验未通过
                prompt("请检查账号或密码格式是否正确！", "error");
            });
        },
        //注册
        register() {
            //表单校验
            this.$refs["registerForm"].validate((valid) => {
                //校验通过
                if (valid) {
                    //获取公钥
                    request.get(
                        "key/getPublicKey"
                    ).then(result => {
                        let backupRegisterData = this.backup(this.registerData);
                        //加密登录数据
                        this.registerData = this.encrypt(result.data.publicKey, this.registerData);
                        request.post(
                            "/user/register",
                            this.registerData
                        ).then(result => {
                            //提示信息
                            prompt(result.message, result.type);
                            //注册成功清除表单内容并切换到登录界面
                            if (result.code === "200") {
                                this.toRegisterOrLogin();
                                this.$refs["registerForm"].resetFields();
                                return;
                            }
                            this.registerData = this.recovery(this.registerData, backupRegisterData);
                        });
                    });
                    return;
                }
                //校验未通过
                prompt("请检查注册信息是否正确！", "error");
            })
        },
        backup(data) {
            let backupData = {
                userAccount: data.userAccount,
                userPWD: data.userPWD,
                userPWD2: data.userPWD2 ? data.userPWD2 : null,
                userName: data.userName ? data.userName : null,
                userPhone: data.userPhone ? data.userPhone : null,
                userEmail: data.userEmail ? data.userEmail : null
            }
            return backupData;
        },
        recovery(data, recoryData) {
            data.userAccount = recoryData.userAccount;
            data.userPWD = recoryData.userPWD;
            data.userPWD2 = data.userPWD2 ? recoryData.userPWD2 : null;
            return data;
        },
        //加密
        encrypt(publicKey, data) {
            data.userAccount = encrypt(publicKey, data.userAccount);
            data.userPWD = encrypt(publicKey, data.userPWD);
            data.userPWD2 = data.userPWD2 ? encrypt(publicKey, data.userPWD2) : null;
            return data;
        },
        //忘记密码
        forgetPassword() {
            prompt("请联系后台管理员重置密码！", "success");
        },
    }
}
</script>